<?php

namespace App\Traits;
use Illuminate\Support\Facades\Log;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Registry;
trait Logs {
    /**
     * 自定义log文件日志
     * @param string $name
     * @return Logger|\Psr\Log\LoggerInterface
     */
    public function getLogger(string $name = "common")
    {
        $bool = Registry::hasLogger($name);
        if($bool)
            return Registry::getInstance($name);
//        $file = storage_path("logs/".date("Ymd")."/".$name.".log");
        $file = storage_path("logs/".date("Ymd").$name.".log");
        if(config("logging.log_path")){
            $file = config("logging.log_path") . "/".date("Ymd").$name.".log";
        }
        $output = "[%datetime%] [%channel%.%level_name%: %message%]: %context% \n";
        $dateFormat = "Y-m-d H:i:s";
        try {
            $formatter = new LineFormatter($output, $dateFormat);
            $handler = new StreamHandler($file,config('logging.log_level',Logger::DEBUG));
            $handler->setFormatter($formatter);
            $logger = new Logger($name,[$handler]);
            Registry::addLogger($logger,$name);
        }catch (\Exception $e){

            $logger = Log::channel(config("logging.default"));
        }
        return $logger;
    }
}
